package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author DiXiaoNie
 * @since 2023/1/3 9:48
 */
@Service
public class AppAssociateServiceImpl implements AppAssociateService {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 自动补全
     *
     * @param dto dto
     * @return {@link ResponseResult }
     * @author DiXiaoNie
     * @date 2023/01/03
     */
    @Override
    public ResponseResult complete(UserSearchDto dto) {
        try {
            SearchRequest searchRequest = new SearchRequest("app_info_article");
            //执行自动补全
            searchRequest.source().suggest(new SuggestBuilder()
                    //指定自动补全的名称，方便后期数据解析
                    .addSuggestion("mySuggestion"
                            //指定自动补全实施的字段名称
                            , SuggestBuilders.completionSuggestion("suggestion")
                                    //根据关键字作为前缀
                                    .prefix(dto.getSearchWords())
                                    //跳过相同数据
                                    .skipDuplicates(true)
                                    //最后显示10条
                                    .size(dto.getPageSize())
                    ));
            //es中搜索并返回符合要求的数据
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

            Suggest suggest = searchResponse.getSuggest();
            CompletionSuggestion mySuggestion = suggest.getSuggestion("mySuggestion");
            List<CompletionSuggestion.Entry.Option> options = mySuggestion.getOptions();
            List<String> collect = new ArrayList<>(options.size());
            collect = options.stream()
                    .map(option -> option.getText().toString())
                    .collect(Collectors.toList());
            return ResponseResult.okResult(collect);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID.getCode(), "出错");
        }
    }
}
